package com.moss.cloud.common.core.utils.file;

import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.*;
@Slf4j
public class ImageReadExample {
    //配置队列大小
    private static final int queueCapacity = 100;
    //配置线程池中的线程的名称前缀
    private static final String namePrefix = "MOSS-ASYNC";
    //线程池维护线程所允许的空闲时间
    private static final int keepAliveSeconds = 60;

    // 如下代碼是自定義讀取圖片的實例代碼
    public static void main(String[] args) {
        // 多線程異步讀取
        //asyncReadImage();
        // 多線程同步讀取
        //syncReadImage();
        // 使用内存映射方式加载大图片
        //readMemoryMapping();
        // 阈值讀取
        readSmartImage();
    }

    public static void readSmartImage(){
        try {
            BufferedImage image = SmartImageLoader.from("D:\\我的图片\\社区资料图文\\auth_1.png")
                    .withSizeThreshold(5 * 1024 * 1024L)  // 2MB阈值
                    .withBlockSize(512)                   // 512x512块大小
                    .withMaxDimension(2048)               // 最大2048px
                    .withExecutor(asyncServiceExecutor())
                    .withCallback(new SmartImageLoader.SimpleImageLoadCallback())
                    .load();
            ImageIO.write(image,"png",new File("D:\\我的图片\\社区资料图文\\auth_1_1.png"));
            System.out.println("閾值讀取"+image.getHeight());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static Executor asyncServiceExecutor() {
        log.info("初始化异步线程池");
        //获取cpu核心数，最大线程数和核心线程数为cpu核心数的2倍
        int curSystemThreads = Runtime.getRuntime().availableProcessors() * 2;
        log.info("系统可用线程池个数:{}", curSystemThreads);
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //配置核心线程数
        executor.setCorePoolSize(curSystemThreads);
        //配置最大线程数
        executor.setMaxPoolSize(curSystemThreads);
        //配置队列大小
        executor.setQueueCapacity(queueCapacity);
        //配置线程池中的线程的名称前缀
        executor.setThreadNamePrefix(namePrefix);
        //线程池维护线程所允许的空闲时间
        executor.setKeepAliveSeconds(keepAliveSeconds);
        // rejection-policy：当pool已经达到max size的时候，如何处理新任务
        // CALLER_RUNS：不在新线程中执行任务，而是有调用者所在的线程来执行--拒绝策略
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        //执行初始化
        executor.initialize();
        //等待所有任务结束后再关闭线程池
        executor.setWaitForTasksToCompleteOnShutdown(true);
        // 使用阿里巴巴的ttl使得父子线程共享变量
        return executor;
    }
}
